<template>
  <el-dialog
    :title="id?'修改文章':'新增文章'"
    :visible.sync="addVisible"
    width="65%"
    :before-close="close"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="文章标题:" prop="title">
        <el-input
          v-model="form.title"
          placeholder="请输入文章标题"
        />
      </el-form-item>
      <el-form-item label="文章内容:" prop="articleBody">
        <quillEditor v-model="form.articleBody" :options="editorOption" />
      </el-form-item>
      <el-form-item label="视频地址:">
        <el-input
          v-model="form.videoURL"
          placeholder="请输入视频地址"
        />
      </el-form-item>
    </el-form>
    <div style="text-align:right"><el-button @click="close">取消</el-button>
    <el-button type="primary" @click="add">确认</el-button></div>
  </el-dialog>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { add, update } from '@/api/hmmm/articles.js'
export default {
  props: {
    id: {
      required: true
    },
    details: {
      type: Object
    }
  },
  components: {
    quillEditor
  },
  data () {
    return {
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            ['blockquote'],
            ['code-block', 'image', 'link'] // 上传图片、上传视频
          ]
        }
      },
      addVisible: false,
      form: {
        id: this.id,
        title: null,
        articleBody: null,
        videoURL: null
      },
      rules: {
        title: { required: true, message: '请输入文章标题' },
        articleBody: { required: true, message: '请输入视频地址' }
      }
    }
  },
  watch: {
    addVisible (val) {
      if (!val) {
        this.form = {
          id: this.id,
          title: null,
          articleBody: null,
          videoURL: null
        }
        this.$refs.form.resetFields()
      }
    },
    id (val) {
      console.log(val)
      if (val) {
        this.form = {
          id: this.id,
          title: this.details.title,
          articleBody: this.details.articleBody,
          videoURL: this.details.videoURL
        }
      }
    }
  },
  methods: {
    close () {
      this.addVisible = false
    },
    add () {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (!this.id) await add(this.form)
          else await update(this.form)
          this.$message.success('操作成功')
          this.$emit('list')
          this.close()
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.quill-editor {
  ::v-deep .ql-editor {
    min-height: 200px;
  }
}
</style>
